package badugi;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author agurgul
 * A deck contains set of {@link Card}s to be drawn and set of used {@link Card}s that is a {@link Deck} too.
 */
public class Deck extends ArrayList<Card>{
	/**
	 * Another {@link Deck} that is used for the storage of already used cards. When there are no more cards
	 * on a {@link Deck} cards from the usedCards deck would be copied to the Deck. See <code>Deck.newCards</code>.
	 */
	private ArrayList<Card> usedCards;

	public ArrayList<Card> getUsedCards() {
		return usedCards;
	}

	/**
	 * Public constructor that creates 52 cards and adds them to itself.
	 */
	public Deck (){
		super(); //Czy to potrzebne?

		usedCards = new ArrayList<>( 52 );

		Ranks[] ranks = Ranks.values();
		Suits[] suits = Suits.values();

		for (Suits suit : suits){
			for (Ranks rank : ranks){
				this.add(new Card(suit, rank));
			}
		}
		shuffle();
	}

	/**
	 * Public method for drawing a card from the top of the {@link Deck}.
	 * @return Card from the top of {@link Deck}
	 */
	public Card drawCard() {
		if (isEmpty()){
			this.newCards();
			return this.remove( this.size() - 1 );
		}
		return this.remove( this.size() - 1 );
	}
	/**
	 * Private method that shuffles {@link Card}s from the deck. It has linear time. According the bridge rule
	 * the deck will be shuffled 7 times.
	 */
	private void shuffle(){
		Collections.shuffle( this );
	}
	/**
	 * When cards on a {@link Deck} are over newCards is called. It moves cards from usedCards to the Deck.
	 * After doing so it shuffles the Deck.
	 */
	private void newCards(){
		for (Card card : usedCards){
			this.add(card);
		}
		usedCards = new ArrayList<Card>();
		this.shuffle();
	}
}
